package com.google.project.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.project.client.Service.DailyReportService;
import com.google.project.server.entity.DailyReport;
import com.google.project.server.entity.DailyReportDetail;
import com.google.project.server.entity.Project;
import com.google.project.server.entity.ProjectTask;
import com.google.project.shared.DailyReportDTO;
import com.google.project.shared.DailyReportDetailDTO;
import com.google.project.shared.ProjectTaskDTO;

@SuppressWarnings("serial")
public class DailyReportServiceImpl extends RemoteServiceServlet implements
		DailyReportService {
	//gui dailyReport
	@Override
	public DailyReportDTO addDailyReport(DailyReportDTO dailyReportDTO,String projectId,List<DailyReportDetailDTO> listReportDetail) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		DailyReport dailyReport = null;
		if (dailyReportDTO.getId() !=null &&  !dailyReportDTO.getId().equalsIgnoreCase("")) {
			//updateSubConstructor(dailyReportDTO);

		} else {
			try {
				//kiểm tra báo cáo đã tồn tại, nếu tồn tại thì cập nhập lại workTofinish(trừ đi cũ) 
				//update lại status của Dailyreport=3 và DailyreportDetail=3
				checkDailyReportExist(dailyReportDTO,projectId); 
				//add mới
				 Project project =   pm.getObjectById(Project.class, projectId);
				 dailyReport = new DailyReport(dailyReportDTO);
				 project.getListOfdailyReport().add(dailyReport);
				 pm.makePersistent(project);
			     addListReportDetail(dailyReport.getId(),listReportDetail,projectId);
				 
			} finally {
				pm.close();
			}
		}
		return dailyReport.toDTO();
	}
	public void checkDailyReportExist(DailyReportDTO dailyReportDTO,String projectId){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Project currProject=pm.getObjectById(Project.class,projectId);
		ProjectServiceImpl projectServer = new ProjectServiceImpl();
		ProjTaskServiceImpl taskServiceImpl = new ProjTaskServiceImpl();
		ProjectTaskDTO projectTaskDTO=new ProjectTaskDTO();
		List<DailyReport> listReport=currProject.getListOfdailyReport();
		try{
			for (DailyReport dailyReport : listReport) {
				if((dailyReportDTO.getReportForDate().longValue()==dailyReport.getReportForDate().longValue()) && (dailyReport.getStatus()!=3)){
					//báo cáo ngày đã tồn tại
					//update lại báo cáo ngày (xóa hết thông số đã thêm vào trước đó)
					List<DailyReportDetail> listDetailReport=dailyReport.getListOfReportDetail();
					for (DailyReportDetail dailyReportDetail : listDetailReport) {
						//get projectTask
						ProjectTask projectTask=pm.getObjectById(ProjectTask.class,dailyReportDetail.getTaskId());
						
						if(projectTask.getStatus()==0)
						{
							projectTask.setStatus(1);
							//canUse
							//projectTask.setStartDate(CommonFuntion.removeTime(new Date(listReportDetailDTO.getCreatedOnDate())));
							taskServiceImpl.startWork(projectTask.toDTO());
						}
						
						projectTaskDTO =projectTask.toDTO();
						//get finishedWork hien tai cua tung task
					
						//update finishedWork  projectTask
						if(projectTaskDTO.getFinishedWork()==null){
							projectTaskDTO.setFinishedWork(0d);
						}
						Double currentFinishedWork=projectTaskDTO.getFinishedWork();
						projectTaskDTO.setFinishedWork(currentFinishedWork-dailyReportDetail.getWorkToFinished());
						projectTask.updateFromDTO(projectTaskDTO);
					//	dailyReportDetail.setProjectId(projectTask.getProjectId());
						//get listReportDetail
						
						 if(projectTaskDTO.getParentId()!=0)
						 {
							 List<ProjectTaskDTO> listTask = projectServer.getListTask(projectId);
							 Double work =dailyReportDetail.getWorkToFinished();
							 
							 taskServiceImpl.updateWorkOfParent(projectTaskDTO, work, listTask);
						 }
						 //update status cua reportDetail =3
						 DailyReportDetailDTO reportDetailDTO=dailyReportDetail.toDTO();
						 reportDetailDTO.setStatus(3);
						 dailyReportDetail.updateFromDTO(reportDetailDTO);
						
						 
					}
					//update status cua dailyReport =3
					 DailyReportDTO _dailyReport=dailyReport.toDTO();
					 _dailyReport.setStatus(3);
					 dailyReport.updateFromDTO(_dailyReport);
					break;
				}
			}
		}catch(Exception ex){
			ex.getMessage();
		}
		
	}
	//truyen vao 1 list DailyReportDetailDTO va dailyReportId
	void addListReportDetail(String dailyReportId,
			List<DailyReportDetailDTO> list ,String projectId) {
		ProjTaskServiceImpl taskServiceImpl = new ProjTaskServiceImpl();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		DailyReportDetail dailyReportDetail = null;
		ProjectTaskDTO projectTaskDTO=new ProjectTaskDTO();
		//get current DailyReport
		DailyReport dailyReport =   pm.getObjectById(DailyReport.class, dailyReportId);
		ProjectServiceImpl projectServer = new ProjectServiceImpl();
		
		
		//duyet list ReportDetail
		for (DailyReportDetailDTO listReportDetailDTO : list) {
			//get projectTask
			ProjectTask projectTask=pm.getObjectById(ProjectTask.class,listReportDetailDTO.getTaskId());
			
			if(projectTask.getStatus()==0)
			{
				projectTask.setStatus(1);
				//canUse
				//projectTask.setStartDate(CommonFuntion.removeTime(new Date(listReportDetailDTO.getCreatedOnDate())));
				taskServiceImpl.startWork(projectTask.toDTO());
			}
			
			projectTaskDTO =projectTask.toDTO();
			//get finishedWork hien tai cua tung task
		
			//update finishedWork  projectTask
			if(projectTaskDTO.getFinishedWork()==null){
				projectTaskDTO.setFinishedWork(0d);
			}
			Double currentFinishedWork=projectTaskDTO.getFinishedWork();
			projectTaskDTO.setFinishedWork(currentFinishedWork+listReportDetailDTO.getWorkToFinished());
			projectTask.updateFromDTO(projectTaskDTO);
			listReportDetailDTO.setProjectId(projectTask.getProjectId());
			//get listReportDetail
			
			 if(projectTaskDTO.getParentId()!=0)
			 {
				 List<ProjectTaskDTO> listTask = projectServer.getListTask(projectId);
				 Double work =listReportDetailDTO.getWorkToFinished();
				 
				 taskServiceImpl.updateWorkOfParent(projectTaskDTO, work, listTask);
				 //taskServiceImpl.updateWorkOfParent(projectTaskDTO.getParentId(), work);
			 }
			 dailyReportDetail = new DailyReportDetail(listReportDetailDTO);
			 dailyReport.getListOfReportDetail().add(dailyReportDetail);
			 pm.makePersistent(dailyReport);
			
		}

	}
	//get dailyReport by ProjectID
	@Override
	public List<DailyReportDTO> getDailyReportByProjectId(String ProjectId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<DailyReportDTO> list = new ArrayList<DailyReportDTO>();
		Project project=pm.getObjectById(Project.class,ProjectId);
		if(project!=null){
			for(int i=0;i<project.getListOfdailyReport().size();i++){
				//list.add(project.getListOfdailyReport().get(i).toDTO());
				DailyReportDTO data=new DailyReportDTO();
				DailyReport dailyReport=new DailyReport();
				dailyReport=project.getListOfdailyReport().get(i);
				if(dailyReport.getListOfReportDetail().size()>0){
				data=project.getListOfdailyReport().get(i).toDTO();	
				data.setProjectID(project.getProjectId());
				data.setProjectName(project.getProjectName());
				list.add(data);
				}
			}
		}
		return list;
	}
	
	/*
	 * get dailyReport by ProjectID and PMId ,du an moi
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<DailyReportDTO> getDailyReportByPM(String userId,int status) {
		List<DailyReportDTO> list = new ArrayList<DailyReportDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String whereStr = " userId ==  \"" + userId + "\"";
		Query q = pm.newQuery(Project.class,whereStr);
		try {
			List<Project> listProj = (List<Project>) q.execute();
			for (Project project : listProj) {
				// projectList.add(project.toDTO());
				if (project.getListOfdailyReport() != null
						&& project.getListOfdailyReport().size() > 0) {
					for (int i = 0; i < project.getListOfdailyReport().size(); i++) {
						if(project.getListOfdailyReport().get(i).getStatus()==status){
							DailyReportDTO data=new DailyReportDTO();
							data=project.getListOfdailyReport().get(i).toDTO();	
							data.setProjectID(project.getProjectId());
							data.setProjectName(project.getProjectName());
							list.add(data);
						}
					}
				}
			}
		} catch (Exception e) {
			// logger.warning(e.getMessage());
		} finally {
			pm.close();
		}
		return list;

	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<DailyReportDTO> getAllDailyReport(){
		List<DailyReportDTO> listDTO = new ArrayList<DailyReportDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(DailyReport.class);
		try {
			List<DailyReport> listReport = (List<DailyReport>) q.execute();
			for (DailyReport dailyReport : listReport) {
				listDTO.add(dailyReport.toDTO());
			}
		} catch (Exception e) {
			// logger.warning(e.getMessage());
		} finally {
			pm.close();
		}
		return listDTO;
	}
	//update dailyReport status
	@Override
	public void updateStatusDailyReport(String id,int status) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		DailyReport dailyReport = null;
		try {
			dailyReport = pm
					.getObjectById(DailyReport.class, id);
			DailyReportDTO data=new DailyReportDTO();
			data=dailyReport.toDTO();
			data.setStatus(status);
			dailyReport.updateFromDTO(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}
	@Override
	public boolean checkDateReport(List<DailyReportDetailDTO> listReport,Long dateReport){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		boolean flag=true;
		for (DailyReportDetailDTO dailyReportDetailDTO : listReport) {
			ProjectTask task=pm.getObjectById(ProjectTask.class, dailyReportDetailDTO.getTaskId());
			if(dateReport<task.getStartDate() || dateReport>task.getDueDate()){
				flag=false;
				break;
			}
		}
		return flag;
	}
}
